<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">
          {{getTitleByName(nameOfPermission)}}列表查询
          <el-button link @click="delFav()" style="margin-bottom: 5px;" v-if="userFavorites?.length > 0">
            <svg-icon icon-class="stars" color="#E6A23C" />
          </el-button>
          <el-button link @click="addFav()" style="margin-bottom: 5px;" v-else>
            <svg-icon icon-class="star" />
          </el-button>
        </div>
        <div>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item prop="budgetOneCollectType" label="汇总数据类型">
          <el-select v-model="listQuery.budgetOneCollectType" class="m-2" placeholder="请选择">
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getEnumList('BudgetCollectType')" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item prop="budgetOneCollectCode" label="汇总数据编码">
          <InputTagDialog v-model="listQuery.budgetOneCollectCode" placeholder="汇总数据编码" title="填写汇总数据编码" />
        </el-form-item>
        <el-form-item prop="budgetOneCollectName" label="汇总数据名称">
          <el-input v-model="listQuery.budgetOneCollectName" placeholder="汇总数据名称" />
        </el-form-item>
        <el-form-item prop="ysySync" label="预算域同步状态">
          <el-select v-model="listQuery.ysySync" class="m-2" placeholder="请选择">
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getEnumList('BudgetCollectSync')" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">列表详情</div>
        <div>
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Edit" @click="handleAdd1">
            查看预算数据
          </el-button>
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Edit" @click="handleAdd2">
            新增汇总预算数据
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="汇总数据类型" prop="budgetOneCollectType" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('BudgetCollectType')" :enum-key="row.budgetOneCollectType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="汇总数据编码" prop="budgetOneCollectCode" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><CodeTag :code="row.budgetOneCollectCode" /></template>
      </el-table-column>
      <el-table-column align="center" label="汇总数据名称" prop="budgetOneCollectName" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.budgetOneCollectName }}</template>
      </el-table-column>
      <el-table-column align="center" label="一级项目" prop="projectOneId" min-width="105px" show-overflow-tooltip>
        <template v-slot="{row}">{{ getIdLabel(projectOneList, row.projectOneId, "name") }}</template>
      </el-table-column>
      <el-table-column align="center" label="组织架构" prop="organizationId" min-width="105px" show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="organizationList" :foreignIds="row.organizationId" :foreignLabel="'organizationName'" /></template>
      </el-table-column>
      <el-table-column align="center" label="单位" prop="governmentId" min-width="105px" show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="governmentList" :foreignIds="row.governmentId" :foreignLabel="'governmentName'" /></template>
      </el-table-column>
      <el-table-column align="center" label="汇总金额" prop="totalAmount" min-width="125px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><MoneyTag :money="row.totalAmount" /></template>
      </el-table-column>
      <el-table-column align="center" label="批复金额" prop="approveAmount" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><MoneyTag :money="row.approveAmount" /></template>
      </el-table-column>
      <el-table-column align="center" label="预算域同步状态" prop="ysySync" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('BudgetCollectSync')" :enum-key="row.ysySync" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="预算域同步结果" prop="ysySyncResult" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.ysySyncResult }}</template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button v-show="checkAuthByCode('')"
                     type="primary"
                     link
                     @click="handleEdit(row)"
                     v-if="['0','2'].includes(row.ysySync)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('') && ['0','2'].includes(row.ysySync)">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
          <el-button v-show="checkAuthByCode('')"
                     type="success"
                     link
                     @click="handleSync(row)"
                     v-if="row.budgetOneCollectType === '0' && ['0','2'].includes(row.ysySync)">同步预算域</el-button>
          <el-button v-show="checkAuthByCode('')"
                     type="primary"
                     link
                     @click="handleSetApproveAmount(row)"
                     v-if="row.budgetOneCollectType === '0' && ['1'].includes(row.ysySync)">录入批复金额</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="汇总数据类型" prop="budgetOneCollectType">
          <el-select v-model="obj.budgetOneCollectType" class="m-2" placeholder="请选择" :disabled="['edit_approveAmount'].indexOf(dialogType) >= 0" clearable filterable>
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getEnumList('BudgetCollectType')" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="汇总数据编码" prop="budgetOneCollectCode">
          <el-input v-model="obj.budgetOneCollectCode" placeholder="请输入汇总数据编码，最多输入100个字符" :disabled="['edit_approveAmount'].indexOf(dialogType) >= 0" />
        </el-form-item>
        <el-form-item label="汇总数据名称" prop="budgetOneCollectName">
          <el-input v-model="obj.budgetOneCollectName" placeholder="请输入汇总数据名称，最多输入200个字符" :disabled="['edit_approveAmount'].indexOf(dialogType) >= 0" />
        </el-form-item>
        <el-form-item label="一级项目" prop="projectOneId" v-if="obj.budgetOneCollectType === '2'">
          <el-select v-model="obj.projectOneId" class="m-2" placeholder="请选择" :disabled="['edit_approveAmount'].indexOf(dialogType) >= 0" clearable filterable>
            <el-option v-for="item in projectOneList" :key="item.id" :label="`${item.code} - ${item.name}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="组织架构" prop="organizationId" v-if="obj.budgetOneCollectType === '3'">
          <Organization v-model="obj.organizationId" keyName="id" keyShow="organizationName" placeholder="组织架构" title="部门查询" />
        </el-form-item>
        <el-form-item label="单位" prop="governmentId" v-if="['4','5'].indexOf(obj.budgetOneCollectType) >= 0">
          <el-select v-model="obj.governmentId" class="m-2" placeholder="请选择" :disabled="['edit_approveAmount'].indexOf(dialogType) >= 0" clearable filterable>
            <el-option v-for="item in projectOneList" :key="item.id" :label="`${item.code} - ${item.name}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="汇总金额" prop="totalAmount">
          <el-input v-model="obj.totalAmount" type="number" placeholder="请输入汇总金额" :disabled="['edit_approveAmount'].indexOf(dialogType) >= 0" />
        </el-form-item>
        <el-form-item label="一下批复金额" prop="approveAmount" v-if="obj.budgetOneCollectType === '0'">
          <el-input-number v-model="obj.approveAmount" :min="1" :max="obj.totalAmount" placeholder="请输入一下批复金额" />
        </el-form-item>
        <el-form-item label="预算域同步状态" prop="ysySync" v-if="obj.budgetOneCollectType === '0'">
          <el-select v-model="obj.ysySync" class="m-2" placeholder="请选择" :disabled="['edit_approveAmount'].indexOf(dialogType) >= 0" clearable filterable>
            <el-option v-for="item in getEnumList('BudgetCollectSync')" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
          <span style="margin-left: 20px;color: #888;">手工调整一下预算批复金额时状态无法修改</span>
        </el-form-item>
        <el-form-item label="预算域同步结果" prop="ysySyncResult" v-if="obj.budgetOneCollectType === '0'">
          <el-input v-model="obj.ysySyncResult" :autosize="{ minRows: 2, maxRows: 5}" type="textarea" :disabled="['edit_approveAmount'].indexOf(dialogType) >= 0" />
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import {alertErrorMsg, customValidator, getListPageSize, notifySuccess} from "@/config/common"
import InputTagDialog from "@/components/InputTag/inputTagDialog.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  budgetOneCollectType: null, // 汇总数据类型
  budgetOneCollectCode: null, // 汇总数据编码
  budgetOneCollectName: null, // 汇总数据名称
  organizationId: null, // 组织架构ID
  projectOneId: null, // 一级项目ID
  totalAmount: null, // 汇总金额
  approveAmount: null, // 一下批复金额
  ysySync: null, // 预算域同步状态
  ysySyncResult: null, // 预算域同步结果
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null
}

export default {
  name: 'budgetOneCollect_nocache',
  components: {Organization, SvgIcon, InputTagDialog},
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        budgetOneCollectType: null,
        budgetOneCollectCode: null,
        budgetOneCollectName: null,
        organizationId: null,
        projectOneId: null,
        totalAmount: null,
        approveAmount: null,
        ysySync: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        budgetOneCollectType: [{ required: true, validator: customValidator, min: 0, max: 100, label: '汇总数据类型', trigger: ['blur', 'change'] }],
        budgetOneCollectCode: [{ required: false, validator: customValidator, min: 0, max: 100, label: '汇总数据编码', trigger: ['blur', 'change'] }],
        budgetOneCollectName: [{ required: true, validator: customValidator, min: 0, max: 200, label: '汇总数据名称', trigger: ['blur', 'change'] }],
        organizationId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '组织架构ID', trigger: ['blur', 'change'] }],
        projectOneId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '一级项目ID', trigger: ['blur', 'change'] }],
        totalAmount: [{ required: false, validator: customValidator, min: 0, max: 13, label: '汇总金额', trigger: ['blur', 'change'] }],
        approveAmount: [{ required: false, validator: customValidator, min: 0, max: 13, label: '一下批复金额', trigger: ['blur', 'change'] }],
        ysySync: [{ required: false, validator: customValidator, min: 0, max: 20, label: '预算域同步状态', trigger: ['blur', 'change'] }],
        ysySyncResult: [{ required: false, validator: customValidator, min: 0, max: 0, label: '预算域同步结果', trigger: ['blur', 'change'] }],
      },
      projectOneList: initListStore().projectOneList,
      organizationList: initListStore().organizationList,
      governmentList: initListStore().governmentList,
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.nameOfPermission = 'budgetOneCollect'
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    this.getList()
    // this.initList()
  },
  methods: {
    // async initList() {
    //   let p1 = doGet(this.svc, '/budget-project-one/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(this.svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let p3 = doGet(this.svc, '/government/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1, p2, p3])
    //   this.projectOneList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    //   this.governmentList = resArray[2]['records']
    // },
    getList() {
      this.listLoading = true
      doGet(this.svc, '/customBudgetOne/queryBudgetOneCollectTotalAmount', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.goTargetByName('budgetOneCollectEdit2', {tab: '2', id: row.id})
    },
    handleView(row) {
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
    },
    handleExport() {
      doGetDownload(this.svc, '/budget-one-collect/export', this.listQuery)
    },
    async handleSync(row) {
      let c = await this.$confirm('您确定要同步到预算域吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      if (c === 'confirm') {
        row.ysySync = '1'
        doPut(this.svc, '/budget-one-collect/modify', row).then(() => {
          notifySuccess('修改成功')
          this.getList()
          this.dialogVisible = false
        })
      }
    },
    handleSetApproveAmount(row) {
      this.dialogType = 'edit_approveAmount'
      this.dialogTypeTitle = '录入批复金额'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
      if (this.obj.approveAmount === null) {
        this.obj.approveAmount = 0
      }
      this.obj.ysySync = '3';
      this.rules.approveAmount[0].maxValue = this.obj.totalAmount
      this.rules.approveAmount[0].required = true
    },
    handleDelete(row) {
      doDelete(this.svc, '/budget-one-collect/' + row.id, {}).then(_ => {
        notifySuccess('操作成功')
        this.getList()
      })
    },
    handleAdd1() {
      this.goTargetByName('budgetOneCollectEdit1', {tab: '1'})
    },
    handleAdd2() {
      this.goTargetByName('budgetOneCollectEdit2', {tab: '2'})
    },
    handleAdd3() {
      this.goTargetByName('budgetOneCollectEdit3', {tab: '3'})
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      switch (this.dialogType) {
        case "add":
          doPost(this.svc, '/budget-one-collect/add', this.obj).then(() => {
            notifySuccess('新增成功')
            this.getList()
            this.dialogVisible = false
          })
          break;
        case "edit":
          this.obj.ysySync = '0'
          doPut(this.svc, '/budget-one-collect/modify', this.obj).then(() => {
            notifySuccess('修改成功')
            this.getList()
            this.dialogVisible = false
          })
          break;
        case "edit_approveAmount":
          this.obj.ysySync = '3';
          doPut(this.svc, '/budget-one-collect/modify', this.obj).then(() => {
            notifySuccess('修改成功')
            this.getList()
            this.dialogVisible = false
          })
          break;
      }
    }
  }
}
</script>
